package com.example.ymm.modules1.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.model.em.EmOrderType;
import com.example.ymm.modules1.controller.BaseController;
import com.example.ymm.modules1.entity.hl.yw.YwApprove;
import com.example.ymm.modules1.entity.my.user.*;
import com.example.ymm.modules1.query.kq.*;
import com.example.ymm.modules1.service.dd.DingdingCheckService;
import com.example.ymm.modules1.service.dto.heng.kq.*;
import com.example.ymm.modules1.service.hl.YwApproveService;
import com.example.ymm.modules1.service.hl.kq.*;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.UtilValidate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/hl/user/production")
@Api(tags = "生产管理")
@Slf4j
@CrossOrigin
public class ProductionController extends BaseController {


    @Autowired
    KqDeptService kqDeptService;

    @Autowired
    DingdingCheckService dingdingCheckService;

    @Autowired
    KqUserService kqUserService;

    @Autowired
    DbUserService dbUserService;

    @Autowired
    KqDakaLogService kqDakaLogService;

    @Autowired
    KqRuleService kqRuleService;

    @Autowired
    KqGroupRuleService kqGroupRuleService;

    @Autowired
    KqApproveLogService kqApproveLogService;
    @Autowired
    YwApproveService ywApproveService;
    @Autowired
    private KqDayLogService kqDayLogService;


    @ApiOperation(value = "车间小组管理")
    @RequestMapping(value = "/kqDeptList", method = RequestMethod.POST)
    public CommonResult kqDeptList(@Valid KqDeptQueryCriteria criteria, YmPageDto ymPage) {
        try{
            TableList<KqDept> list = kqDeptService.list(criteria, ymPage);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "车间小组下拉")
    @RequestMapping(value = "/kqDeptSelect", method = RequestMethod.POST)
    public CommonResult kqDeptSelect() {
        try{
            List<KqDept> list = kqDeptService.queryAll(null);
            JSONObject json=new JSONObject();
            json.put("list",list);
            String userName=getUserName();
            KqDept kqDept = kqDeptService.findByGroupAndManageName(userName);
            String groupId="";
            if(UtilValidate.isNotEmpty(kqDept)){
                groupId=kqDept.getId();
            }
            json.put("groupId",groupId);
            return CommonResult.success(json,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "车间小组保存")
    @RequestMapping(value = "/kqDeptSave", method = RequestMethod.POST)
    public CommonResult kqDeptSave(@Valid KqDept kqDept) {
        try{
            if(UtilValidate.isEmpty(kqDept.getCheJianName())){
                return CommonResult.error("非法参数");
            }
            kqDeptService.saveOrUpdate(kqDept);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "车间小组删除")
    @RequestMapping(value = "/kqDeptRemove", method = RequestMethod.POST)
    public CommonResult kqDeptRemove(@Valid KqDept kqDept) {
        try{
            kqDeptService.removeById(kqDept);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "车间考勤人员管理")
    @RequestMapping(value = "/kqUserList", method = RequestMethod.POST)
    public CommonResult kqUserList(KqUserQueryCriteria criteria, YmPageDto ymPage) {
        try{
            String userName=getUserName();
            KqDept kqDept = kqDeptService.findByGroupUserName(userName);
            if(UtilValidate.isNotEmpty(kqDept)){
                criteria.setGroupUserId(kqDept.getGroupUserId());
            }
            KqDept kqDept2 = kqDeptService.findByManageUserName(userName);
            if(UtilValidate.isNotEmpty(kqDept2)){
                criteria.setManageUserId(kqDept2.getManageUserId());
            }
            String userRole = getUserRole();
            if(!userRole.equals("manage")&&kqDept==null&&kqDept2==null){
                return CommonResult.error("暂无权限");
            }
            TableList<ViewKqUser> list = kqUserService.list(criteria, ymPage);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "车间考勤人员保存")
    @RequestMapping(value = "/kqUserSave", method = RequestMethod.POST)
    public CommonResult kqUserSave(@Valid KqUser kqUser) {
        try{
            if(UtilValidate.isEmpty(kqUser.getUserName())){
                return CommonResult.error("非法参数");
            }
            if(UtilValidate.isEmpty(kqUser.getUserId())){
                DbUser user = dbUserService.findByUserName(kqUser.getUserName());
                if(UtilValidate.isEmpty(user)){
                    return CommonResult.error("查找不到人员请检查输入名称!");
                }else{
                    kqUser.setUserId(user.getUserId());
                }
                KqUser byId = kqUserService.getById(kqUser.getUserId());
                if(UtilValidate.isNotEmpty(byId)){
                    return CommonResult.error("该人员已在名单中!");
                }
            }
            kqUserService.saveOrUpdate(kqUser);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "导入考勤人员")
    @RequestMapping(value = "/importKqUser", method = RequestMethod.POST)
    public CommonResult importKqUser(@RequestBody ImportKqUserDto dto) {
        try{
            if(UtilValidate.isEmpty(dto.getGroupId())){
                return CommonResult.error("请选择车间小组!");
            }
            if(UtilValidate.isEmpty(dto.getList())){
                return CommonResult.error("人员名单不能为空!");
            }
            List<String> strings = kqUserService.importKqUser(dto);
            return CommonResult.success(strings);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "删除考勤人员")
    @RequestMapping(value = "/removeKqUser", method = RequestMethod.POST)
    public CommonResult removeKqUser(@RequestParam String userId) {
        try{
            kqUserService.removeById(userId);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取列定义")
    @RequestMapping(value = "/getattcolumns", method = RequestMethod.POST)
    public CommonResult getattcolumns() {
        try{
            JSONObject getattcolumns = dingdingCheckService.getattcolumns();
            return CommonResult.success(getattcolumns);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "打卡记录-手机")
    @RequestMapping(value = "/kqDaKaLogList", method = RequestMethod.POST)
    public CommonResult kqDaKaLogList(KqDakaLogQueryCriteria criteria, YmPageDto ymPage) {
        try{
//            if(UtilValidate.isEmpty(userId)){
//                userId="272814054637816231";
//            }
//            JSONObject getcolumnval = dingdingCheckService.getcolumnval(userId,columnIdList);
            String userName=getUserName();
            KqDept kqDept = kqDeptService.findByGroupUserName(userName);
            if(UtilValidate.isNotEmpty(kqDept)){
                criteria.setGroupUserId(kqDept.getGroupUserId());
            }
            KqDept kqDept2 = kqDeptService.findByManageUserName(userName);
            if(UtilValidate.isNotEmpty(kqDept2)){
                criteria.setManageUserId(kqDept2.getManageUserId());
            }
            if(criteria.getPlatform()==null||UtilValidate.isNotEmpty(criteria.getPlatform())&&!criteria.getPlatform().equals("pc")){
                if(UtilValidate.isEmpty(criteria.getGroupUserId())
                        &&UtilValidate.isEmpty(criteria.getManageUserId())){
                    criteria.setGroupUserId("NULL");
                }
            }

            TableList<ViewKqDakaLog> list = kqDakaLogService.list(criteria, ymPage);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "打卡记录-pc")
    @RequestMapping(value = "/pcDaKaLogList", method = RequestMethod.POST)
    public CommonResult pcDaKaLogList(KqDakaLogQueryCriteria criteria, YmPageDto ymPage) {
        try{
//            if(UtilValidate.isEmpty(userId)){
//                userId="272814054637816231";
//            }
//            JSONObject getcolumnval = dingdingCheckService.getcolumnval(userId,columnIdList);
            String userName=getUserName();

            String userRole = getUserRole();
            if(!"manage".equals(userRole)){
                KqDept kqDept = kqDeptService.findByGroupUserName(userName);
                if(UtilValidate.isNotEmpty(kqDept)){
                    criteria.setGroupUserId(kqDept.getGroupUserId());
                }
                KqDept kqDept2 = kqDeptService.findByManageUserName(userName);
                if(UtilValidate.isNotEmpty(kqDept2)){
                    criteria.setManageUserId(kqDept2.getManageUserId());
                }
                if(criteria.getPlatform()==null||UtilValidate.isNotEmpty(criteria.getPlatform())&&!criteria.getPlatform().equals("pc")){
                    if(UtilValidate.isEmpty(criteria.getGroupUserId())
                            &&UtilValidate.isEmpty(criteria.getManageUserId())){
                        criteria.setGroupUserId("NULL");
                    }
                }
            }


            TableList<ViewKqDakaLog> list = kqDakaLogService.list(criteria, ymPage);//list  pcList
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "获取缺卡记录")
    @RequestMapping(value = "/lackUserDakas", method = RequestMethod.POST)
    public CommonResult lackUserDakas(KqDakaLogQueryCriteria criteria, YmPageDto ymPage) {
        try{
//            if(UtilValidate.isEmpty(userId)){
//                userId="272814054637816231";
//            }
//            JSONObject getcolumnval = dingdingCheckService.getcolumnval(userId,columnIdList);
            String userName=getUserName();
            KqDept kqDept = kqDeptService.findByGroupUserName(userName);
            if(UtilValidate.isNotEmpty(kqDept)){
                criteria.setGroupUserId(kqDept.getGroupUserId());
            }
            KqDept kqDept2 = kqDeptService.findByManageUserName(userName);
            if(UtilValidate.isNotEmpty(kqDept2)){
                criteria.setManageUserId(kqDept2.getManageUserId());
            }
            List<ViewKqDakaLog> kqDakaLogs = kqDakaLogService.lackUserDakas(criteria);
            return CommonResult.success(kqDakaLogs);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }




    @ApiOperation(value = "审批打卡记录")
    @RequestMapping(value = "/approvalDakaTableList", method = RequestMethod.POST)
    public CommonResult approvalDakaTableList(KqApproveLogQueryCriteria criteria, YmPageDto ymPage) {
        try{
            TableList<ViewKqDakaLog> list = kqDakaLogService.approvalTableList(criteria, ymPage);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "打卡记录详情")
    @RequestMapping(value = "/kqDaKaLogDetail", method = RequestMethod.POST)
    public CommonResult kqDaKaLogDetail(@RequestParam String id) {
        try{
            ViewKqDakaLog detail = kqDakaLogService.detail(id);
            return CommonResult.success(detail);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "前端计算全天时长")
    @RequestMapping(value = "/countDakaDetail", method = RequestMethod.POST)
    public CommonResult countDakaDetail(@RequestBody ViewKqDakaLog viewKqDakaLog) {
        try{
            ViewKqDakaLog detail = kqDakaLogService.countDakaDetail(viewKqDakaLog);
            return CommonResult.success(detail);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "保存打卡数据")
    @RequestMapping(value = "/saveDakaDetail", method = RequestMethod.POST)
    public CommonResult saveDakaDetail(@RequestBody ViewKqDakaLog viewKqDakaLog) {
        try{
            if(UtilValidate.isEmpty(viewKqDakaLog.getUserId())){
                return CommonResult.error("非法参数!");
            }
            String s = kqDakaLogService.saveDakaDetail(viewKqDakaLog);
            return CommonResult.success(s);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "获取休息记录")
    @RequestMapping(value = "/getUserXiuxiDetail", method = RequestMethod.POST)
    public CommonResult getUserXiuxiDetail(@RequestBody ViewKqDakaLog viewKqDakaLog) {
        try{
            if(UtilValidate.isEmpty(viewKqDakaLog.getUserId())){
                return CommonResult.error("非法参数!");
            }
            String s = kqDakaLogService.saveDakaDetail(viewKqDakaLog);
            return CommonResult.success(s);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "考勤规则列表")
    @RequestMapping(value = "/ruleList", method = RequestMethod.POST)
    public CommonResult ruleList(KqRuleQueryCriteria criteria, YmPageDto ymPage) {
        try{
            TableList<KqRule> list = kqRuleService.list(criteria, ymPage);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "导入考勤规则")
    @RequestMapping(value = "/importKqRule", method = RequestMethod.POST)
    public CommonResult importKqRule(@RequestBody List<KqRule> list) {
        try{
            if(UtilValidate.isEmpty(list)){
                return CommonResult.error("非法参数!");
            }
            List<String> strings = kqRuleService.importRule(list);
            return CommonResult.success(strings);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "删除考勤规则")
    @RequestMapping(value = "/removeKqRule", method = RequestMethod.POST)
    public CommonResult removeKqRule(@RequestParam String id) {
        try{
            kqRuleService.removeById(id);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "设置考勤组规则")
    @RequestMapping(value = "/settingGroupRule", method = RequestMethod.POST)
    public CommonResult settingGroupRule(@RequestParam String deptIds, @RequestParam String ruleId) {
        try{
            if(UtilValidate.isEmpty(deptIds)){
                return CommonResult.error("数据不能为空!");
            }
            kqGroupRuleService.settingGroupRule(deptIds, ruleId);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "考勤组规则列表")
    @RequestMapping(value = "/groupRuleList", method = RequestMethod.POST)
    public CommonResult groupRuleList(KqGroupRuleQueryCriteria criteria, YmPageDto ymPage) {
        try{

            TableList<ViewGroupRule> list = kqGroupRuleService.list(criteria, ymPage);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "删除考勤组规则")
    @RequestMapping(value = "/removeGroupRule", method = RequestMethod.POST)
    public CommonResult removeGroupRule(@RequestParam String id) {
        try{
            kqGroupRuleService.removeById(id);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "查询是否可以提交审批")
    @RequestMapping(value = "/approveCount", method = RequestMethod.POST)
    public CommonResult approveCount(KqApproveLogQueryCriteria criteria) {
        try{
            DbApprovalLog l = kqApproveLogService.approveCount(criteria);
            if(UtilValidate.isEmpty(l)){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("approveLog", null);
                jsonObject.put("addDate", criteria.getAddDate());
                return CommonResult.success(jsonObject);
            }
            YwApprove byApproveNo = ywApproveService.findByApproveNo(l.getApproveNo());
            l.setApprove(byApproveNo);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("approveLog", l);
            jsonObject.put("addDate", criteria.getAddDate());
            boolean izCan=true;
            if(UtilValidate.isNotEmpty(l)){
                if(l.getStatus().equals(1)||l.getStatus().equals(2)){
                    izCan=false;
                }
            }

            jsonObject.put("izCan", izCan);
            return CommonResult.success(jsonObject);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "前端计算全天时长")
    @RequestMapping(value = "/batchUpDakaLog", method = RequestMethod.POST)
    public CommonResult batchUpDakaLog(@RequestBody ViewApproveDakaLog viewKqDakaLog) {
        try{
//             kqDakaLogService.batchUpDakaLog(viewKqDakaLog);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "查询人员当月休息记录")
    @RequestMapping(value = "/getXiuxiList", method = RequestMethod.POST)
    public CommonResult getXiuxiList(KqApproveLogQueryCriteria criteria) {
        try{
            List<KqApproveLog> list=kqApproveLogService.getXiuxiList(criteria);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "考勤统计")
    @RequestMapping(value = "/userDaysCountTable", method = RequestMethod.POST)
    public CommonResult userDaysCountTable(@RequestBody UserDayLogQueryCriteria criteria) {
        try{
            String userName=getUserName();

            if(UtilValidate.isEmpty(criteria.getGroupIdIn())){
                KqDeptQueryCriteria c1=new KqDeptQueryCriteria();
                c1.setGroupUserName(userName);
                List<KqDept> kqDepts = kqDeptService.queryAll(c1);
                List<String> groupIdIn=new ArrayList<>();
                if(UtilValidate.isNotEmpty(kqDepts)){
                    for(KqDept kqDept:kqDepts){
                        groupIdIn.add(kqDept.getId());
                    }
                }
                criteria.setGroupIdIn(groupIdIn);
            }
            if(UtilValidate.isNotEmpty(criteria.getMonth())){
                String month = criteria.getMonth();
                String start=month+"-01 00:00:00";
                String end = DateKit.getNextMonthStartDate(start);
                criteria.setStartTime(start);
                criteria.setEndTime(end);
            }
            YmPageDto pageDto=new YmPageDto();
            pageDto.setPageSize(criteria.getPageSize());
            pageDto.setPage(criteria.getPage());
            TableList<UserDayLogDto> list = kqDayLogService.userDaysCountTable(criteria, pageDto);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取个人所在考勤组")
    @RequestMapping(value = "/getUserGroupIdIn", method = RequestMethod.POST)
    public CommonResult getUserGroupIdIn() {
        try{

            String userName=getUserName();

            KqDeptQueryCriteria c1=new KqDeptQueryCriteria();
            c1.setGroupUserName(userName);
            List<KqDept> kqDepts = kqDeptService.queryAll(c1);


            List<String> groupIdIn=new ArrayList<>();
            if(UtilValidate.isNotEmpty(kqDepts)){
                for(KqDept kqDept:kqDepts){
                    groupIdIn.add(kqDept.getId());
                }
            }
            return CommonResult.success(groupIdIn);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "个人考勤情况")
    @RequestMapping(value = "/userDayListTable", method = RequestMethod.POST)
    public CommonResult userDayListTable(KqDakaLogQueryCriteria criteria, YmPageDto ymPageDto) {
        try{

            if(UtilValidate.isNotEmpty(criteria.getMonth())){
                String month = criteria.getMonth();
                String start=month+"-01 00:00:00";
                String end = DateKit.getNextMonthStartDate(start);
                criteria.setStartTime(start);
                criteria.setEndTime(end);
            }
            TableList<ViewKqDakaLog> list = kqDakaLogService.list(criteria, ymPageDto);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


}
